﻿/* SleepyLabs is a simple clean shutdown/restart application for XenServer
 * Copyright (C) 2010 Stephen Rice
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Web: http://code.google.com/p/sleepylabs/
 * Date: 15/06/2010
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;

namespace SleepyLabs
{
    /// <summary>
    /// Coordinates expensive or long running tasks which would block the UI
    /// thread from updating. Uses a queue system and executes each task
    /// sequentially, firing off events as it starts and finishes the queue.
    /// 
    /// The task manager also takes a reference to some UI which it invokes
    /// updates to, showing which tasks it is currently processing.
    /// 
    /// NOTE: Although basic queue and lock systems are in place the 
    /// interactive UI is currently designed to disable after a task is added 
    /// to the task manager.
    /// </summary>
    class TaskManager
    {
        private BackgroundWorker workerThread;
        private object newTaskLock = new object();
        private Queue<WorkTask> workQueue = new Queue<WorkTask>();

        // The UI to update as the tasks progress
        private ToolStripProgressBar progressBar;
        private ToolStripStatusLabel statusLabel;

        public EventHandler<EventArgs> AllTasksFinished;
        public EventHandler<EventArgs> TasksStarted;

        public TaskManager(ToolStripProgressBar ProgressBar, ToolStripStatusLabel StatusLabel)
        {
            progressBar = ProgressBar;
            statusLabel = StatusLabel;
        }

        public bool IsBusy
        {
            get { return workerThread != null; }
        }

        public void AddTask(DoWorkEventHandler method, object args, string title)
        {
            lock (newTaskLock)
            {
                if (workerThread == null)
                {
                    workerThread = new BackgroundWorker();
                    workerThread.DoWork += method;
                    workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);
                    workerThread.RunWorkerAsync(args);
                    progressBar.Visible = true;
                    statusLabel.Visible = true;
                    statusLabel.Text = title;
                }
                else
                {
                    workQueue.Enqueue(new WorkTask(method, args, title));
                }
                if (TasksStarted != null)
                    TasksStarted.Invoke(this, null);
            }
        }

        void workerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                MessageBox.Show(string.Format(Messages.ENCOUNTERED_AN_ERROR_W_DETAIL, e.Error.Message), statusLabel.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            lock (newTaskLock)
            {
                if (workQueue.Count == 0)
                {
                    workerThread = null;
                    progressBar.Visible = false;
                    statusLabel.Visible = false;
                    if (AllTasksFinished != null)
                        AllTasksFinished.Invoke(this, null);

                    return;
                }
                WorkTask nextTask = workQueue.Dequeue();
                workerThread = new BackgroundWorker();
                workerThread.DoWork += nextTask.method;
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);
                workerThread.RunWorkerAsync(nextTask.args);
                statusLabel.Text = nextTask.title;
            }
        }

        class WorkTask
        {
            public DoWorkEventHandler method;
            public object args;
            public string title;

            public WorkTask(DoWorkEventHandler method, object args, string title) 
            {
                this.args = args;
                this.title = title;
                this.method = method;
            }
        }
    }
}
